<?php
/**
 * 物资库存，入库，入库明细
 */
namespace App\Http\Controllers\Api;
use App\Model\Users;
use App\Model\Goods;
use App\Model\Stock;
use App\Model\MaterialList;
use App\Model\WarehouseMaterials;
use App\Model\Checkcategory;
use App\Model\Company;
use App\Model\WarehouseOrder;
use App\Model\WarehouseOutboundDetail;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\SimpleType\TblWidth;


class WarehouseMaterialsController extends Controller
{

    /**
     * 物资库存管理列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouseMaterialslistdata(Request $request)
    {
        $query = $this->warehouseMaterialspub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();
        $get_warehouse_type = WarehouseMaterials::get_warehouse_type();

        $res_arr['data']['list'] = $res['data'];
        $res_arr['data']['count'] = $res['total'];
        $res_arr['data']['get_warehouse_type'] = $get_warehouse_type;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 导出物资库存管理列表
     * @param $request
     * @return array
     */
    public function warehouseMaterialspub($request){
        $query= WarehouseMaterials::orderby('id','asc');
        if(isset($request['name']) && $name = $request['name']){  //物资名称
            $query->where('name','like','%'.$name.'%');
        }
        if(isset($request['goods_id']) && $goods_id = $request['goods_id']){ //分类名称
            $query->where('goods_id',$goods_id);
        }
        if(isset($request['warehouse_type']) && $warehouse_type = $request['warehouse_type']){ //入库类型
            $query->where('warehouse_type',$warehouse_type);
        }
        if(isset($request['start_created_at']) && $start_created_at = $request['start_created_at']){  //开始时间
            $query->where('created_at','>=',$start_created_at);
        }
        if(isset($request['end_created_at']) && $end_created_at = $request['end_created_at']){  //结束时间
            $query->where('created_at','<=',$end_created_at);
        }
        return $query;
    }

    /**
     * 导出物资库存管理列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function warehouseMaterialsexportone(Request $request)
    {
        $query = $this->warehouseMaterialspub($request);
        $dataExpor= $query->get()->toArray();

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G','H','I');
        $title = [
            'A1'=>'序 号',
            'B1'=>'入库单号',
            'C1'=>'入库时间',
            'D1'=>'物资分类',
            'E1'=>'物资名称',
            'F1'=>'所属单位（人）',
            'G1'=>'入库数量',
            'H1'=>'入库类别',
            'I1'=>'提交人',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($dataExpor as &$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['checkcategory_id']??'');
            $objActSheet->setCellValue("C".$orirow,$val['company_id']??'');
            $objActSheet->setCellValue("D".$orirow,$val['goods_name']??'');
            $objActSheet->setCellValue("E".$orirow,$val['name']??'');
            $objActSheet->setCellValue("F".$orirow,$val['income_warehouse']??'');
            $objActSheet->setCellValue("G".$orirow,$val['warehouse']??'');
            $objActSheet->setCellValue("H".$orirow,$val['leave_warehouse']??'');
            $objActSheet->setCellValue("I".$orirow,$val['loss_warehouse']??'');
            $objActSheet->setCellValue("J".$orirow,$val['address']??'');
            $objActSheet->setCellValue("K".$orirow,$val['leader']??'');
            $objActSheet->setCellValue("L".$orirow,$val['leaderPhone']??'');

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:G1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资库存管理表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 物资入库单记录列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouseOrderListData(Request $request)
    {
        $query = $this->warehouseOrderPub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();
        $get_warehouse_type = WarehouseMaterials::get_warehouse_type();
        /*foreach ($res['data'] as $key=>$val){
            if(isset($val['warehouse_materials'])){
                foreach ($val['warehouse_materials'] as $wk=>$wv){
                    if(empty($wv['material_list'])){
                        unset($res['data'][$key]);
                    }
                }
            }
        }*/
        $res_arr['data']['list'] = $res['data'];
        $res_arr['data']['count'] = $res['total'];
        $res_arr['data']['get_warehouse_type'] = $get_warehouse_type;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资入库单记录列表数据
     * @param $request
     * @return array
     */
    public function warehouseOrderPub($request)
    {
        $user = Auth::user();
        $role = $user->role;
        $community = $user->community;

        $name = $request['name'];
        $query = WarehouseOrder::with([
            'warehouseMaterials',
            'Users:id,name',
            'warehouseMaterials.checkcategory:id,name',
            'warehouseMaterials.goods:id,name',
            'warehouseMaterials.company:id,comName,community',
            'warehouseMaterials.materialList:id,name'])->whereHas('warehouseMaterials.materialList', function ($q) use ($name) {
                if($name){
                    $q->where('name', 'like', '%' . $name . '%');
                }
             });
        if(Users::iscommunity($role)){
            $query = $query->whereHas('warehouseMaterials.company', function ($q) use ($community) {
                $q->where('community', $community);
            });
        }
        //->orderby('id','asc')
        /* if(isset($request['name']) && $name = $request['name']){  //物资名称
             $query->where('warehouseMaterials.materialList.name','like','%'.$name.'%');
         }*/
        if (isset($request['goods_id']) && $goods_id = $request['goods_id']) { //分类名称
            //$query->where('goods_id', $goods_id);
            $query = $query->whereHas('warehouseMaterials', function ($q) use ($goods_id) {
                $q->where('goods_id', $goods_id);
            });
        }
        if (isset($request['warehouse_type']) && $warehouse_type = $request['warehouse_type']) { //入库类型
            $query = $query->where('warehouse_type', $warehouse_type);
        }
        if (isset($request['start_created_at']) && $start_created_at = $request['start_created_at']) {  //开始时间
            $query = $query->where('created_at', '>=', $start_created_at);
        }
        if (isset($request['end_created_at']) && $end_created_at = $request['end_created_at']) {  //结束时间
            $query = $query->where('created_at', '<=', $end_created_at);
        }
        $query = $query->orderby('id','desc');
        return $query;
    }

    /**
     * 导出物物资入库单记录列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function warehouseOrderExportone(Request $request)
    {
        $query = $this->warehouseOrderPub($request);
        $dataExpor= $query->get()->toArray();
        $data = [];
        foreach ($dataExpor as $key=>$val){
            foreach ($val['warehouse_materials'] as $wk=>$wv){
                $wv['order'] = $val['order'];
                $wv['created_at'] = $val['created_at'];
                $wv['warehouse_type'] = WarehouseMaterials::get_warehouse_type($val['warehouse_type']);
                $wv['user_name'] = $val['users']['name'];
                $wv['goods_name'] = $wv['goods']['name']??'';
                $wv['material_list_name'] = $wv['material_list']['name']??'';
                $wv['company_name'] = $wv['company']['comName']??'';
                $data[]=$wv;
            }
        }

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G','H','I');
        $title = [
            'A1'=>'序 号',
            'B1'=>'入库单号',
            'C1'=>'入库时间',
            'D1'=>'物资分类',
            'E1'=>'物资名称',
            'F1'=>'所属单位（人）',
            'G1'=>'入库数量',
            'H1'=>'入库类别',
            'I1'=>'提交人',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($data as &$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['order']??'');
            $objActSheet->setCellValue("C".$orirow,$val['created_at']??'');
            $objActSheet->setCellValue("D".$orirow,$val['goods_name']??'');
            $objActSheet->setCellValue("E".$orirow,$val['material_list_name']??'');
            $objActSheet->setCellValue("F".$orirow,$val['company_name']??'');
            $objActSheet->setCellValue("G".$orirow,$val['number']??'');
            $objActSheet->setCellValue("H".$orirow,$val['warehouse_type']??'');
            $objActSheet->setCellValue("I".$orirow,$val['user_name']??'');

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:I1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资入库记录表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 物资出库记录的单个出库单（新增）
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function warehouseOrderData(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;
        $warehouseOrder = WarehouseOrder::with([
            'warehouseMaterials',
            'Users:id,name',
            'warehouseMaterials.checkcategory:id,name',
            'warehouseMaterials.goods:id,name',
            'warehouseMaterials.materialList:id,name',
            'warehouseMaterials.company:id,comName,leader,leaderPhone'])->where('id', $id)->first();
        if($warehouseOrder){
            $warehouseOrder=$warehouseOrder->toArray();
        }
        $res_arr['data']['warehouseOrder'] = $warehouseOrder;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资入库页面（新增）
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function referweb(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;  //入库单id
        $warehouseOutboundDetail = $this->pub_edit_del($id);
        if($warehouseOutboundDetail==2){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该入库记录不存在，不能修改';
            return response()->json($res_arr);
        }else{
            if($warehouseOutboundDetail){
                $res_arr["code"] = 408;
                $res_arr["message"] = '该物资已出库，不能修改';
                return response()->json($res_arr);
            }
        }


        $warehouseMaterials = WarehouseMaterials::with(['checkcategory:id,name','goods:id,name','materialList:id,name','company:id,comName'])->where('order_id', $id)->get()->toArray();
        if($warehouseMaterials){
            $res_arr['data']['warehouseMaterials'] = $warehouseMaterials;
        }

        $goods = Goods::get()->toArray(); //物资分类
        $materialList = MaterialList::get()->toArray(); //物资名称
        $get_warehouse_type = WarehouseMaterials::get_warehouse_type(); //入库类型
        $checkcategory = Checkcategory::get()->toArray(); //所属单位
        $companys = Company::select('id','comName')->get()->toArray(); //单位名称
        //入库单名称
        $user = Auth::user();
        $companyId = $user->companyId;  //当前用户所属企业
        $company = Company::with(['checkcategory'])->find($companyId);

        $res_arr['data']['goods'] = $goods;
        $res_arr['data']['materialList'] = $materialList;
        $res_arr['data']['get_warehouse_type'] = $get_warehouse_type;
        $res_arr['data']['checkcategory'] = $checkcategory;
        $res_arr['data']['companys'] = $companys;
        $res_arr['data']['warehouse_name'] = $company['checkcategory']['name']??'';
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资入库页面（新增）仅app可用
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function referwebtoapp(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;  //入库单id
        $warehouseOutboundDetail = $this->pub_edit_del($id);
        if($warehouseOutboundDetail==2){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该入库记录不存在，不能修改';
            return response()->json($res_arr);
        }else{
            if($warehouseOutboundDetail){
                $res_arr["code"] = 408;
                $res_arr["message"] = '该物资已出库，不能修改';
                return response()->json($res_arr);
            }
        }


        $warehouseMaterials = WarehouseMaterials::with(['checkcategory:id,name','goods:id,name','materialList:id,name','company:id,comName'])->where('order_id', $id)->get()->toArray();
        $res_arr['data']['warehouseMaterials'] = $warehouseMaterials;

        $goods = Goods::get()->toArray(); //物资分类
        $materialList = MaterialList::get()->toArray(); //物资名称
        $get_warehouse_type = WarehouseMaterials::get_warehouse_type(); //入库类型
        $checkcategory = Checkcategory::get()->toArray(); //所属单位
        //入库单名称
        $user = Auth::user();
        $companyId = $user->companyId;  //当前用户所属企业
        $company = Company::with(['checkcategory'])->find($companyId);
        $res_arr['data']['goods'] = $goods;
        $res_arr['data']['materialList'] = $materialList;
        $res_arr['data']['get_warehouse_type'] = $get_warehouse_type;
        $res_arr['data']['checkcategory'] = $checkcategory;
        $res_arr['data']['warehouse_name'] = $company['checkcategory']['name']??'';
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }
    /**
     * 物资库存管理数据处理
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function warehouseMaterialsRefer(Request $request)
    {
        $redata = $request->all();
        /*$redata['materials'] = [[
            'goods_id'=>15,
            'material_id'=>2,
            'checkcategory_id'=>2,
            'company_id'=>2,
            'number'=>26,
            'unit'=>'单位：青科安全1',
            'norms'=>'规格：件1',
            'remarks'=>'备注备注',
            'seat'=>'具体位置',
            'img_url'=>'\storage\word_static_images\small_zero.png',
        ],[
            'goods_id'=>16,
            'material_id'=>2,
            'checkcategory_id'=>3,
            'company_id'=>7,
            'number'=>27,
            'unit'=>'单位：青科安全',
            'norms'=>'规格：件',
            'remarks'=>'备注备注',
            'seat'=>'具体位置1',
            'img_url'=>'\storage\word_static_images\small_zero.png',
        ]];*/

        $id = isset($redata['id']) ? $redata['id'] : 0;
        $user = Auth::user();
        $userid = $user->id;
        DB::beginTransaction();
        $order_data = WarehouseOrder::where('id',$id)->first();
        if($order_data){
            $order_id = $id;
            Stock::operate_del($id,1);
            //$resu = WarehouseMaterials::where('order_id', $id)->delete();
        }else{
            $insert_order['user_id'] = $userid;
            $insert_order['warehouse_type'] = $redata['warehouse_type'];  //入库类型
            $insert_order['applicant'] = $redata['applicant']??'';  //申请人
            $insert_order['applicant_sign'] = $redata['applicant_sign']??'';  //经办人签字,图片url，只有app用到
            $insert_order['created_at'] = date('Y-m-d H:i:s');
            $url = $request->url();
            if(strstr($url,'/api/')){
                $insert_order['isapp'] = 1;
            }
            $order_id = WarehouseOrder::insertGetId($insert_order);
            if($order_id){
                $order = WarehouseOrder::getorders($order_id);
                $update_order['order'] = $order;
                $warehouseOrder = WarehouseOrder::where('id', $order_id)->update($update_order);
                if(!$warehouseOrder){
                    DB::rollBack();
                    $res_arr["code"] = 408;
                    $res_arr["message"] = 'fail';
                    return response()->json($res_arr);
                }
            }else{
                DB::rollBack();
                $res_arr["code"] = 408;
                $res_arr["message"] = 'fail';
                return response()->json($res_arr);
            }
        }
        if (!is_array($redata['materials'])){
            $redata['materials'] = json_decode($redata['materials'],true);
        }
        foreach ($redata['materials'] as $vkey=>$vm) {
            $ruserData['order_id'] = $order_id;
            $ruserData['goods_id'] = $vm['goods_id'];
            $ruserData['material_id'] = $vm['material_id'];
            $ruserData['checkcategory_id'] = $vm['checkcategory_id'];
            $ruserData['company_id'] = $vm['company_id'];
            $ruserData['number'] = $vm['number'];
            $ruserData['unit'] = $vm['unit']??'';
            $ruserData['norms'] = $vm['norms']??'';
            $ruserData['remarks'] = $vm['remarks'];
            $ruserData['seat'] = $vm['seat']??'';
            $ruserData['img_url'] = $vm['img_url'];
            $ruserData['odd_numbers'] = $vm['odd_numbers']??''; //单号：入库类型warehouse_type2：盘点单号；3：出库单号;
            $ruserData['created_at'] = date('Y-m-d H:i:s');
            $ruserData['user_id'] = $userid;
            $ruserData['warehouse_type'] = $redata['warehouse_type'];
            $ruserData['applicant'] = $redata['applicant']??'';  //申请人
            $res = WarehouseMaterials::insertGetId($ruserData);
            if(!$res){
                DB::rollBack();
                $res_arr["code"] = 408;
                $res_arr["message"] = 'fail';
                return response()->json($res_arr);
            }
            Stock::operate($vm['goods_id'],$vm['material_id'],$vm['checkcategory_id'],$vm['company_id'],1,$redata['warehouse_type'],['unit'=>$ruserData['unit'],'norms'=>$vm['norms']]);
        }
        DB::commit();
        $request['id'] = $order_id;
        $this->storage_import1($request);
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 删除跟修改公用的地方
     * @param $id
     * @return mixed
     */
    public function pub_edit_del($id){
        $data = WarehouseOrder::with(['warehouseMaterials'])->where('id',$id)->first();
        if($id && !$data){
            return 2;
        }
        $goods_ids=$material_ids=$checkcategory_ids=$company_ids=[];
        if($data){
            $data=$data->toArray();
            foreach ($data['warehouse_materials'] as $key=>$val){
                $goods_ids[]=$val['goods_id'];
                $material_ids[]=$val['material_id'];
                $checkcategory_ids[]=$val['checkcategory_id'];
                $company_ids[]=$val['company_id'];
            }
        }
        $stock_data = Stock::whereIn('goods_id',$goods_ids)->whereIn('material_id',$material_ids)->whereIn('checkcategory_id',$checkcategory_ids)->whereIn('company_id',$company_ids)->get()->toarray();
        $stock_ids = array_column($stock_data,'id');
        $warehouseOutboundDetail = WarehouseOutboundDetail::whereIn('stock_id',$stock_ids)->orderby('id','desc')->first();
        if($data && $warehouseOutboundDetail){
            $warehouseOutboundDetail = $warehouseOutboundDetail->toArray();
            if(isset($warehouseOutboundDetail['created_at']) && $warehouseOutboundDetail['created_at']>$data['created_at']){ //最新的出库的时间大于入库时间则该入库不能修改
                return $warehouseOutboundDetail;
            }
        }else{
            return 0;
        }
    }

    /**
     * 入库单删除
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function material_del(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $warehouseOutboundDetail = $this->pub_edit_del($id);
        if($warehouseOutboundDetail==2){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该入库记录不存在，不能删除';
            return response()->json($res_arr);
        }else{
            if($warehouseOutboundDetail){
                $res_arr["code"] = 408;
                $res_arr["message"] = '该物资已出库，不能删除';
                return response()->json($res_arr);
            }
        }
        Stock::operate_del($id,1);
        $resu = WarehouseOrder::where('id', $id)->delete(); //入库单
        //WarehouseMaterials::where('order_id', $id)->delete(); //明细
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 导出入库单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \PhpOffice\PhpWord\Exception\Exception
     */
    public function storage_import(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        /*读取数据*/
        $templateProcessor =  new TemplateProcessor('./word/template/入库单2.docx');
        $data = $this->warehouseOrderData($request);
        $data = json_decode(json_encode($data), true);
        $warehouseOrder = $data['original']['data']['warehouseOrder']??[];
        $templateProcessor->setValue('created_at', date('Y年m月d日',strtotime($warehouseOrder['created_at'])));
        $templateProcessor->setValue('order', $warehouseOrder['order']);
        $checkcategory_name=$company_name='';
        $count_num = 0;
        $user_name = $warehouseOrder['users']['name']??'';
        if (isset($warehouseOrder['warehouse_materials'])){
            $templateProcessor->cloneRow('numb', count($warehouseOrder['warehouse_materials']));
            foreach($warehouseOrder['warehouse_materials'] as $k=>$v) {
                $checkcategory_name = $v['checkcategory']['name']??'';

                $leader = $v['company']['leader']??'';
                $company_name = $v['company']['comName']??'';
                $tmp_arr['goods_name'] = $v['goods']['name']??'';
                $tmp_arr['material_name'] = $v['material_list']['name']??'';
                $tmp_arr['number'] = $v['number']??'';
                $tmp_arr['unit'] = $v['unit']??'';
                $tmp_arr['norms'] = $v['norms']??'';
                $tmp_arr['remarks'] = $v['remarks']??'';
                $count_num = $count_num + $tmp_arr['number'];
                $templateProcessor->setValue('numb#'.($k+1), $k+1);
                //$templateProcessor->style($kk, $vv);
                foreach($tmp_arr as $kk=>$vv) {
                    $templateProcessor->setValue($kk.'#'.($k+1), $vv);
                }
            }
            $templateProcessor->setValue('checkcategory_name', $checkcategory_name);
            $templateProcessor->setValue('company_name', $company_name);
            $templateProcessor->setValue('count_num', $count_num);

            $templateProcessor->setValue('leader', '');

            $applicant_sign=$warehouseOrder['applicant_sign'];
            $file_exists = (@fopen($applicant_sign, "r")) ? true : false;
            if($applicant_sign && $file_exists){ //file_exists($applicant_sign)
                $templateProcessor->setImageValue('user_name', $applicant_sign);
            }else{
                $templateProcessor->setValue('user_name', '');
            }
        }

        $time = time();
        $name="入库单_".$time;
        $path = "./storage/word/".$name.".docx";
        $templateProcessor->saveAs($path);

        return response()->json(['data' => 'http://'.$_SERVER['HTTP_HOST'].$path,'code' => 200], 200);
    }

    public function storage_import1(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        /*读取数据*/
        $templateProcessor =  new TemplateProcessor('./word/template/入库单.docx');
        $data = $this->warehouseOrderData($request);
        $data = json_decode(json_encode($data), true);
        $warehouseOrder = $data['original']['data']['warehouseOrder']??[];
        $templateProcessor->setValue('created_at', date('Y年m月d日',strtotime($warehouseOrder['created_at'])));
        $templateProcessor->setValue('order', $warehouseOrder['order']);
        $checkcategory_name=$company_name='';
        $count_num = 0;
        $user_name = $warehouseOrder['users']['name']??'';

        $cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center'); // 设置可跨行，且文字在居中
        $cellRowContinue = array('vMerge' => 'continue'); //使行连接，且无边框线
        $cellVCentered = array('valign' => 'center'); //居中
        $cellHCentered = array('align' => 'center'); //居中
        $cellHCentered1 = array('align' => 'left'); //
        $fontStyle = array('size'=>12,'bold'=>true,'valign'=>'center','align'=>'center','name'=>'宋体');
        $fontStyle1 = array('size'=>12,'valign'=>'center','align'=>'center','name'=>'宋体');
        $contentStyle = array('size'=>11,'valign'=>'left','align'=>'left','name'=>'宋体');
        $cellColSpan3 = array('gridSpan' => 3, 'valign' => 'center'); //设置跨列
        $table = new Table(array('borderSize' => 6, 'borderColor' => 'black', 'width' => 8500, 'unit' => TblWidth::TWIP)); //array('borderSize' => 6, 'borderColor' => 'black', 'width' => 9500, 'unit' => TblWidth::TWIP)

        /*添加table头部*/
        $table->addRow(600);  //添加一行
        /*$table->addCell(5000,$cellHCentered)->addText("姓名",$styleFoun,$cellHCentered);*/
        $table->addCell(4000, $cellRowSpan)->addText('类 别',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(4000, $cellRowSpan)->addText('序 号',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(7000, $cellRowSpan)->addText('物品名称',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('数 量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('单 位',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('规 格',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('备 注',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中

        // dump($sdata);exit;
        $num = [];
        $arr = $arrs = [];
        $xh=0;
        foreach($warehouseOrder['warehouse_materials'] as $kar=>$v) {
            $tmp_arr = array();
            $tmp_arr['goods_name'] = $v['goods']['name']??'';
            $tmp_arr['xh'] = $kar+1;
            $tmp_arr['material_name'] = $v['material_list']['name']??'';
            $tmp_arr['number'] = $v['number']??'';
            $tmp_arr['unit'] = $v['unit']??'';
            $tmp_arr['norms'] = $v['norms']??'';
            $tmp_arr['remarks'] = $v['remarks']??'';
            $tmp_arr['goods_id'] = $v['goods_id']??'';

            $data['table'][]=$tmp_arr;  //正常赋值用于word中的表格遍历
            $data['real_data'][] = $tmp_arr;//算全部合计的时候用
            $arrs[$v['goods_id']][]=$tmp_arr;

            $checkcategory_name = $v['checkcategory']['name']??'';
            $leader = $v['company']['leader']??'';
            $company_name = $v['company']['comName']??'';
        }
        foreach ($arrs as $k=>$vv){
            foreach ($vv as $kk=>$tmp_arr){
                $xh++;
                $kk++;
                if($kk==1){
                    $table->addRow();  //添加一行
                    $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['goods_name'],$fontStyle1, $cellHCentered); //设置该列可以跨行，且样式居中
                }else{
                    $table->addRow(500);
                    $table->addCell(null, $cellRowContinue);
                }
                $table->addCell(5000, $cellRowSpan)->addText($xh,$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
                $table->addCell(7000, $cellRowSpan)->addText($tmp_arr['material_name'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['number'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['unit'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['norms'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['remarks'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
            }
        }
        $templateProcessor->setValue('checkcategory_name', $checkcategory_name);
        $templateProcessor->setValue('company_name', $company_name);

        $templateProcessor->setValue('leader', '');

        $applicant_sign=$warehouseOrder['applicant_sign'];
        $file_exists = (@fopen($applicant_sign, "r")) ? true : false;
        if($applicant_sign && $file_exists){ //file_exists($applicant_sign)
            $templateProcessor->setImageValue('user_name', $applicant_sign);
        }else{
            $templateProcessor->setValue('user_name', '');
        }

        $real_data = $data['real_data'];
        unset($data['real_data']);
        // 添加总计
        $table->addRow(600);  //添加一行
        $table->addCell(5000, $cellColSpan3)->addText('总计',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellVCentered)->addText(array_sum(array_column($real_data,'number')),$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 //
        $table->addCell(5000, $cellVCentered)->addText('',$contentStyle, $cellHCentered1);
        $table->addCell(5000, $cellVCentered)->addText('',$contentStyle, $cellHCentered1);
        $table->addCell(5000, $cellVCentered)->addText('',$contentStyle, $cellHCentered1);


        $templateProcessor->setComplexBlock('table', $table);

        $time = time();
        $name="入库单_".$time;
        $path = "/storage/word/".$name.".docx";
        $templateProcessor->saveAs('.'.$path);
        $file=$warehouseOrder['file'];
        if($file && file_exists('.'.$file)){
            unlink('.'.$file);
        }

        $update_order['file'] = $path;
        $warehouseOrder = WarehouseOrder::where('id', $id)->update($update_order);
    }

    /**
     * 添加修改时导出入库单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storage_import_url(Request $request){
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $warehouseOrder = WarehouseOrder::where('id', $id)->first();
        $path = $warehouseOrder->file;
        if(empty($warehouseOrder) || !file_exists('.'.$path)){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该入库单不存在，请联系管理员';
            return response()->json($res_arr);
        }

        return response()->json(['data' => 'http://'.$_SERVER['HTTP_HOST'].$path,'code' => 200], 200);
    }

    /**
     * 获取所有入库类型
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouse_type_all(Request $request)
    {
        $get_warehouse_type = WarehouseMaterials::get_warehouse_type(); //状态
        $res_arr['data'] = $get_warehouse_type;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }
}
